// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司 
// SPDX-License-Identifier: GPL-3.0-only 

import { page } from "$app/state";
import type { BoardInfo } from "$lib/api/board/board";
import { get as get_board } from "$lib/api/board/board";
import type { MemberInfo } from "$lib/api/board/board_member";
import { get as get_member } from "$lib/api/board/board_member";
import type { board as board_notice } from '$lib/api/notice_type';
import { get_user_id, get_user_session } from "$lib/api/user";
import { request } from "$lib/utils/request";
import { getCurrentWindow } from "@tauri-apps/api/window";

export class BoardStore {
    public boardId = $derived(page.url.searchParams.get("boardId") ?? "");

    public boardInfo = $state(null as null | BoardInfo);
    public myMember = $state(null as null | MemberInfo);

    async initBoard() {
        this.loadBoardInfo();
        this.loadMyMember();
    }

    private async loadBoardInfo() {
        const sessionId = await get_user_session();
        const res = await request(get_board({
            session_id: sessionId,
            board_id: this.boardId,
        }));
        this.boardInfo = res.board;
    }

    private async loadMyMember() {
        const sessionId = await get_user_session();
        const myUserId = await get_user_id();
        const res = await request(get_member({
            session_id: sessionId,
            board_id: this.boardId,
            member_user_id: myUserId,
        }));
        this.myMember = res.member;
    }

    async processBoardNotice(notice: board_notice.AllNotice) {
        if(notice.UpdateBoardNotice != undefined && notice.UpdateBoardNotice.board_id == this.boardId){
            await this.loadBoardInfo();
        }else if(notice.RemoveBoardNotice != undefined && notice.RemoveBoardNotice.board_id == this.boardId){
            getCurrentWindow().close();
        }else if(notice.UpdateBoardMemberPermNotice != undefined && notice.UpdateBoardMemberPermNotice.board_id == this.boardId && notice.UpdateBoardMemberPermNotice.member_user_id == this.myMember?.member_user_id) {
            await this.loadMyMember();
        }
    }
}

export const boardStore = $state(new BoardStore());